package com.zhj.structure.linear.utils;

/**
 * @PackageName:com.zhj.structure.utils
 * @ClassName:MyStack
 * @auter: 朱慧杰
 * @date:2020/8/8 0008 11:24
 **/
public class MyStack {

    // 栈的底层我们用数组存储
    private int[] elements;

    public MyStack() {
        elements = new int[0];
    }

    // 压入元素
    public void push(int num) {
        int[] newArr = new int[elements.length+1];
        for (int i = 0; i < elements.length; i++) {
            newArr[i] = elements[i];
        }
        newArr[elements.length] = num;
        elements = newArr;
    }

    // 取出栈顶元素
    public int pop() {
        if (elements.length == 0) {
            throw new RuntimeException("栈中没有元素！！！");
        }
        int element = elements[elements.length-1];
        int[] newArr = new int[elements.length-1];
        for (int i = 0; i < elements.length-1; i++) {
            newArr[i] = elements[i];
        }
        elements = newArr;
        return element;
    }

    // 查看栈顶元素
    public int peek() {
        if (elements.length == 0) {
            throw new RuntimeException("栈中没有元素！！！");
        }
        return elements[elements.length-1];
    }

    // 判断栈是否为空
    public boolean isEmpty() {
        return elements.length==0;
    }

}
